import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

class MyTheadPool {
    private BlockingDeque<Runnable> blockingDeque = new LinkedBlockingDeque<>();

    //通过这个方法将任务添加到线程池中
    public void submit(Runnable runnable) throws InterruptedException {
        blockingDeque.put(runnable);
    }

    // n 表示线程池里有几个线程
    // 创建了一个固定数量的线程池
    MyTheadPool(int n) {
        for (int i = 0; i < n; ++i) {
            Thread t = new Thread(() -> {
                //线程池只做一件事,不断循环的取出阻塞队列中的runnable,然后执行
                while (true) {
                    try {
                        // 取出任务, 并执行
                        Runnable runnable = blockingDeque.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            t.start();
        }
    }
}

public class Demo25 {
    public static void main(String[] args) throws InterruptedException {
        MyTheadPool myTheadPool = new MyTheadPool(4);
        for (int i = 0; i < 1000; ++i) {
            myTheadPool.submit(new Runnable() {
                @Override
                public void run() {
                    // 要执行的工作
                    System.out.println(Thread.currentThread().getName() + " hello");
                }
            });
        }
    }
}
